// 游戏引擎核心
class GameEngine {
    constructor() {
        this.currentScene = null;
        this.gameState = {
            chapter: 1,
            scene: 1,
            choices: [],
            flags: {},
            stats: {
                scientific: 0,
                explorer: 0,
                survival: 0
            }
        };
        this.storyData = null;
        this.isLoaded = false;
        this.textSpeed = 3; // 1-5 的文字显示速度
        
        this.init();
    }

    async init() {
        try {
            // 加载故事数据
            await this.loadStoryData();
            
            // 加载设置
            this.loadSettings();
            
            // 绑定事件
            this.bindEvents();
            
            this.isLoaded = true;
            console.log('游戏引擎初始化完成');
        } catch (error) {
            console.error('游戏引擎初始化失败:', error);
        }
    }

    async loadStoryData() {
        // 宏大的多元宇宙时空回音故事 - 5章完整剧情
        this.storyData = {
            chapters: {
                1: {
                    title: "chapter1_title", // 初次觉醒
                    scenes: {
                        1: {
                            id: "chapter1_scene1",
                            title: "chapter1_scene1_title",
                            content: "chapter1_scene1_content",
                            image: "images/lab_night.jpg",
                            choices: [
                                {
                                    id: "choice1_1",
                                    text: "choice1_1",
                                    leads_to: "chapter1_scene2a",
                                    stats: { scientific: 1 }
                                },
                                {
                                    id: "choice1_2", 
                                    text: "choice1_2",
                                    leads_to: "chapter1_scene2b",
                                    stats: { explorer: 1 }
                                },
                                {
                                    id: "choice1_3",
                                    text: "choice1_3", 
                                    leads_to: "chapter1_scene2c",
                                    stats: { survival: 1 }
                                },
                                {
                                    id: "choice1_4",
                                    text: "choice1_4",
                                    leads_to: "chapter1_scene2d",
                                    stats: { intuitive: 1 }
                                }
                            ]
                        },
                        "2a": {
                            id: "chapter1_scene2a",
                            title: "数据分析",
                            content: "你迅速检查设备的数据读数。屏幕上显示着异常的能量波动，量子场强度超出了正常范围的300%。这些数据表明，某种未知的现象正在发生。你意识到这可能是一个重大的科学发现...",
                            image: "images/data_screen.jpg",
                            choices: [
                                {
                                    id: "choice2a_1",
                                    text: "记录所有数据并深入分析",
                                    leads_to: "chapter1_scene3a",
                                    stats: { scientific: 1 }
                                },
                                {
                                    id: "choice2a_2",
                                    text: "尝试重现这种现象",
                                    leads_to: "chapter1_scene3b",
                                    stats: { explorer: 1 }
                                }
                            ]
                        },
                        "2b": {
                            id: "chapter1_scene2b", 
                            title: "接近未知",
                            content: "你小心翼翼地靠近发光的设备。蓝光变得更加明亮，你感受到一种奇特的能量波动。当你伸手触碰设备时，突然间，周围的时空似乎开始扭曲...",
                            image: "images/blue_glow.jpg",
                            choices: [
                                {
                                    id: "choice2b_1",
                                    text: "继续触碰设备",
                                    leads_to: "chapter1_scene3c",
                                    stats: { explorer: 1 }
                                },
                                {
                                    id: "choice2b_2",
                                    text: "立即退后并观察",
                                    leads_to: "chapter1_scene3d",
                                    stats: { survival: 1 }
                                }
                            ]
                        },
                        "2c": {
                            id: "chapter1_scene2c",
                            title: "安全第一",
                            content: "你立即启动了紧急关闭程序，所有设备开始按序关闭。但奇怪的是，那个发光的设备似乎无法关闭，蓝光反而变得更加强烈。你意识到情况比预想的更加复杂...",
                            image: "images/emergency_shutdown.jpg",
                            choices: [
                                {
                                    id: "choice2c_1",
                                    text: "联系安全部门寻求帮助",
                                    leads_to: "chapter1_scene3e",
                                    stats: { survival: 1 }
                                },
                                {
                                    id: "choice2c_2",
                                    text: "尝试手动断开设备电源",
                                    leads_to: "chapter1_scene3f",
                                    stats: { scientific: 1 }
                                }
                            ]
                        },
                        // 第三层场景 - 结局分支
                        "3a": {
                            id: "chapter1_scene3a",
                            title: "科学的发现",
                            content: "通过详细的数据分析，你发现了时空波动的规律。这一发现将改变人类对时间和空间的理解。你决定将这一发现公之于众，造福全人类。",
                            image: "images/scientific_discovery.jpg",
                            isEnding: true,
                            endingType: "scientific_hero"
                        },
                        "3b": {
                            id: "chapter1_scene3b",
                            title: "时空门户",
                            content: "当你尝试重现现象时，一个稳定的时空门户打开了。你成为了第一个时空旅行者，开启了人类探索多元宇宙的新纪元。",
                            image: "images/portal_opened.jpg",
                            isEnding: true,
                            endingType: "explorer_pioneer"
                        },
                        "3c": {
                            id: "chapter1_scene3c",
                            title: "时空融合",
                            content: "当你触碰设备的瞬间，你与量子场发生了融合。你获得了操控时空的能力，但也承担着巨大的责任。",
                            image: "images/time_fusion.jpg",
                            isEnding: true,
                            endingType: "fusion_being"
                        },
                        "3d": {
                            id: "chapter1_scene3d",
                            title: "观察者效应",
                            content: "你的观察改变了量子现象的性质。设备最终稳定下来，但你意识到观察者的意识在量子层面的重要性。",
                            image: "images/observer_effect.jpg",
                            isEnding: true,
                            endingType: "quantum_observer"
                        },
                        "3e": {
                            id: "chapter1_scene3e",
                            title: "团队合作",
                            content: "在安全团队的帮助下，异常现象得到了安全控制。虽然错过了独自探索的机会，但确保了所有人的安全。",
                            image: "images/team_safety.jpg",
                            isEnding: true,
                            endingType: "safety_first"
                        },
                        "3f": {
                            id: "chapter1_scene3f",
                            title: "意外穿越",
                            content: "当你切断电源的瞬间，时空发生了撕裂。你被意外传送到了一个平行世界，开始了新的冒险。",
                            image: "images/parallel_world.jpg",
                            isEnding: true,
                            endingType: "accidental_traveler"
                        }
                    }
                }
            }
        };
    }

    loadSettings() {
        const settings = JSON.parse(localStorage.getItem('timeecho_settings') || '{}');
        this.textSpeed = settings.textSpeed || 3;
        
        // 更新UI元素
        const textSpeedSlider = document.getElementById('textSpeed');
        if (textSpeedSlider) {
            textSpeedSlider.value = this.textSpeed;
        }
    }

    saveSettings() {
        const settings = {
            textSpeed: this.textSpeed
        };
        localStorage.setItem('timeecho_settings', JSON.stringify(settings));
    }

    bindEvents() {
        // 设置相关事件
        const textSpeedSlider = document.getElementById('textSpeed');
        if (textSpeedSlider) {
            textSpeedSlider.addEventListener('input', (e) => {
                this.textSpeed = parseInt(e.target.value);
                this.saveSettings();
            });
        }
    }

    startNewGame() {
        this.gameState = {
            chapter: 1,
            scene: 1,
            choices: [],
            flags: {},
            stats: {
                scientific: 0,
                explorer: 0,
                survival: 0
            }
        };
        
        this.loadScene(1, 1);
        
        // 记录成就
        if (window.achievementSystem) {
            window.achievementSystem.unlock('first_choice');
        }
    }

    loadScene(chapter, scene) {
        // 首先尝试从大型剧情系统加载
        const sceneId = `chapter${chapter}_scene${scene}`;
        if (window.megaStoryExpansion) {
            const megaStory = window.megaStoryExpansion.getDynamicStory(sceneId, this.gameState.choices || []);
            if (megaStory) {
                this.currentStory = megaStory;
                this.displayScene(megaStory);
                console.log(`🎆 加载扩展剧情: ${sceneId}`);
                return;
            }
        }
        
        // 回退到原始剧情系统
        const sceneData = this.getSceneData(chapter, scene);
        if (!sceneData) {
            console.error(`场景不存在: Chapter ${chapter}, Scene ${scene}`);
            return;
        }

        this.currentScene = sceneData;
        this.gameState.chapter = chapter;
        this.gameState.scene = scene;

        // 更新UI
        this.displayScene(sceneData);
        
        // 自动保存
        this.autoSave();
    }

    getSceneData(chapter, scene) {
        const chapterData = this.storyData.chapters[chapter];
        if (!chapterData) return null;
        
        return chapterData.scenes[scene];
    }

    displayScene(sceneData) {
        // 更新场景标题
        const sceneTitle = document.getElementById('sceneTitle');
        if (sceneTitle) {
            sceneTitle.textContent = window.i18n.get(sceneData.title);
        }

        // 更新场景图片
        const sceneImg = document.getElementById('sceneImg');
        if (sceneImg && sceneData.image) {
            sceneImg.src = sceneData.image;
            sceneImg.alt = window.i18n.get(sceneData.title);
        }

        // 动画显示故事内容
        this.displayStoryContent(sceneData.content);

        // 显示选择按钮
        this.displayChoices(sceneData.choices);

        // 更新章节信息
        const chapterNum = document.getElementById('chapterNum');
        if (chapterNum) {
            chapterNum.textContent = this.gameState.chapter;
        }

        // 如果是结局，显示结局UI
        if (sceneData.isEnding) {
            this.handleEnding(sceneData);
        }
    }

    displayStoryContent(contentKey) {
        const storyContent = document.getElementById('storyContent');
        if (!storyContent) return;

        const text = window.i18n.get(contentKey);
        const speed = 50 - (this.textSpeed * 8); // 转换速度值

        // 清空内容
        storyContent.textContent = '';

        // 逐字显示动画
        let index = 0;
        const showChar = () => {
            if (index < text.length) {
                storyContent.textContent += text[index];
                index++;
                setTimeout(showChar, speed);
            }
        };

        showChar();
    }

    displayChoices(choices) {
        const choicesContainer = document.getElementById('choicesContainer');
        if (!choicesContainer) return;

        // 清空现有选择
        choicesContainer.innerHTML = '';

        if (!choices || choices.length === 0) return;

        // 添加选择按钮
        choices.forEach((choice, index) => {
            const button = document.createElement('button');
            button.className = 'choice-btn fade-in';
            button.textContent = window.i18n.get(choice.text);
            button.style.animationDelay = `${index * 0.1}s`;
            
            button.addEventListener('click', () => {
                this.makeChoice(choice);
            });

            choicesContainer.appendChild(button);
        });
    }

    makeChoice(choice) {
        // 记录选择
        this.gameState.choices.push(choice.id);

        // 更新统计数据
        if (choice.stats) {
            Object.keys(choice.stats).forEach(stat => {
                this.gameState.stats[stat] = (this.gameState.stats[stat] || 0) + choice.stats[stat];
            });
        }

        // 应用选择后果（如果有的话）
        if (window.megaStoryExpansion && window.megaStoryExpansion.choiceConsequences[choice.id]) {
            const consequence = window.megaStoryExpansion.choiceConsequences[choice.id];
            if (consequence.statsModifier) {
                Object.keys(consequence.statsModifier).forEach(stat => {
                    this.gameState.stats[stat] = (this.gameState.stats[stat] || 0) + consequence.statsModifier[stat];
                });
            }
            console.log(`🎆 应用选择后果: ${choice.id}`);
        }

        // 检查成就
        this.checkAchievements();

        // 跳转到下一个场景
        if (choice.leads_to) {
            this.loadSceneById(choice.leads_to);
        }
    }

    loadSceneById(sceneId) {
        // 解析场景ID (格式: chapter1_scene2a)
        const match = sceneId.match(/chapter(\d+)_scene(.+)/);
        if (!match) {
            console.error('无效的场景ID:', sceneId);
            return;
        }

        const chapter = parseInt(match[1]);
        const scene = match[2];
        
        this.loadScene(chapter, scene);
    }

    checkAchievements() {
        if (!window.achievementSystem) return;

        // 检查不同的成就条件
        const stats = this.gameState.stats;
        
        if (stats.scientific >= 3) {
            window.achievementSystem.unlock('scientist');
        }
        
        if (stats.explorer >= 3) {
            window.achievementSystem.unlock('explorer');
        }
        
        if (stats.survival >= 3) {
            window.achievementSystem.unlock('survivor');
        }
    }

    handleEnding(sceneData) {
        // 记录结局
        if (!this.gameState.flags.endings) {
            this.gameState.flags.endings = [];
        }
        
        if (!this.gameState.flags.endings.includes(sceneData.endingType)) {
            this.gameState.flags.endings.push(sceneData.endingType);
        }

        // 检查是否解锁了所有结局
        if (this.gameState.flags.endings.length >= 6) {
            window.achievementSystem.unlock('all_endings');
        }

        // 显示结局选项
        setTimeout(() => {
            this.showEndingOptions();
        }, 3000);
    }

    showEndingOptions() {
        const choicesContainer = document.getElementById('choicesContainer');
        if (!choicesContainer) return;

        choicesContainer.innerHTML = '';
        
        const restartBtn = document.createElement('button');
        restartBtn.className = 'choice-btn';
        restartBtn.textContent = window.i18n.get('restart_question');
        restartBtn.addEventListener('click', () => {
            this.startNewGame();
        });

        const menuBtn = document.createElement('button');
        menuBtn.className = 'choice-btn';
        menuBtn.textContent = window.i18n.get('menu');
        menuBtn.addEventListener('click', () => {
            window.uiManager.showMainMenu();
        });

        choicesContainer.appendChild(restartBtn);
        choicesContainer.appendChild(menuBtn);
    }

    saveGame() {
        const saveData = {
            gameState: this.gameState,
            timestamp: Date.now()
        };
        
        localStorage.setItem('timeecho_save', JSON.stringify(saveData));
        
        // 显示保存成功提示
        this.showNotification(window.i18n.get('gameSaved'));
    }

    loadGame() {
        const saveData = JSON.parse(localStorage.getItem('timeecho_save'));
        if (!saveData) {
            this.showNotification(window.i18n.get('noSaveData'));
            return false;
        }

        this.gameState = saveData.gameState;
        this.loadScene(this.gameState.chapter, this.gameState.scene);
        
        this.showNotification(window.i18n.get('gameLoaded'));
        return true;
    }

    autoSave() {
        const autoSaveEnabled = document.getElementById('autoSave')?.checked !== false;
        if (autoSaveEnabled) {
            this.saveGame();
        }
    }

    showNotification(message) {
        // 创建通知元素
        const notification = document.createElement('div');
        notification.className = 'notification fade-in';
        notification.textContent = message;
        notification.style.cssText = `
            position: fixed;
            top: 20px;
            left: 50%;
            transform: translateX(-50%);
            background: rgba(0, 212, 255, 0.9);
            color: white;
            padding: 10px 20px;
            border-radius: 8px;
            z-index: 1000;
            backdrop-filter: blur(10px);
        `;

        document.body.appendChild(notification);

        // 3秒后移除
        setTimeout(() => {
            notification.remove();
        }, 3000);
    }

    getGameState() {
        return this.gameState;
    }

    hasUnsavedProgress() {
        return this.gameState.choices.length > 0;
    }
}

// 创建全局游戏引擎实例
window.gameEngine = new GameEngine();